<template>
  <code-rain class="code-rain-background"></code-rain>


  <div class="personal_card">
    <div class="card_left">
      <div class="img" @click="handleToOther">
        <img :src="posts.userAvatar" alt="头像" />
      </div>
      <div class="name">
        <span>{{ posts.username }}</span>
      </div>
      <div class="fans">
        <span>粉丝:{{ fans }}</span>
        <span>关注:{{ followed }}</span>
        <div>
          <span>分类：</span>
          <span class="tag" @click="handleSearchPost(posts.tags)">#{{posts.tags}}</span>
        </div>
      </div>
    </div>
    <div class="card_middle">
      <div class="follow" v-if="!isOwner">
        <el-button
          :type="isFollowing ? 'danger' : 'primary'"
          @click="handleFollow"
        >
          {{ isFollowing ? "取消关注" : "关注" }}
        </el-button>
      </div>
    </div>
  </div>
  <div class="post_content">
    <div class="title">{{ posts.title }}</div>
    <div class="detail_content" v-html="posts.content"></div>
    <div class="like">
      <div class="like_comment">
        <!-- 点赞按钮 -->
        <div @click="handleLike" class="like_button">
          <i :class="['fas fa-heart', { liked: isLiked }]"></i>
          <span>点赞</span>
          <span class="count">{{ likeCount }}</span>
        </div>
        <!-- 评论按钮 -->
        <div @click="showCommentModal = true" class="comment_button">
          <i class="fas fa-comment"></i>
          <span>评论</span>
          <span class="count">{{ posts.commentCount }}</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 评论弹窗 -->
  <el-dialog
    v-model="showCommentModal"
    title="评论"
    width="50%"
    :before-close="handleClose"
  >
    <div class="comment-container">
      <!-- 评论列表 -->
      <div class="comment-list">
        <!-- 一级评论 -->
        <div v-for="(comment, index) in comments" :key="comment.id" class="comment-item">
          <div class="main-comment" @click="prepareReply(comment)">
            <div class="comment-header">
              <span class="floor-number">{{ index + 1 }} 楼</span>
              <span class="comment-user">{{ comment.username }}</span>
            </div>
            <div class="comment-content">
              {{ comment.content }}
            </div>
            <!-- 展开二级评论按钮 -->
            <div class="comment-actions" v-if="comment.replies && comment.replies.length > 0">
              <el-button type="text" @click.stop="toggleReplies(comment)">
                {{ comment.showReplies ? '收起' : '展开' }} ({{ comment.replies.length }})
              </el-button>
            </div>
          </div>

          <!-- 二级评论 -->
          <div v-if="comment.showReplies && comment.replies.length > 0" class="replies">
            <div
              v-for="(reply, replyIndex) in comment.replies"
              :key="reply.id"
              class="reply-item"
              @click.stop="prepareReply(reply)"
            >
              <div class="comment-header">
                <span class="floor-number">{{ index + 1 }}-{{ replyIndex + 1 }} 楼</span>
                <span class="comment-user">{{ reply.username }}</span>
              </div>
              <div class="comment-content">
                {{ reply.content }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="comment-input">
        <el-input
          v-model="newComment"
          :placeholder="replyPlaceholder"
          @keyup.enter="submitComment"
        >
          <template #append>
            <el-button type="primary" @click="submitComment">发送</el-button>
            <el-button v-if="replyTo" type="text" @click="cancelReply" style="position: absolute;right: 90px ">取消回复</el-button>
          </template>
        </el-input>
      </div>
    </div>
  </el-dialog>
</template>


<script setup>
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import { onMounted } from "vue";
import { API_BASE_URL } from "@/config/config";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import codeRain from '@/components/codeRain.vue'
const router = useRouter();
const route = useRoute();
const postId = route.params.id;
//粉丝数量
const fans = ref(0);
//关注数量
const followed = ref(0)
// 存储帖子数据
const posts = ref({});

// 点赞状态
const isLiked = ref(false);
const likeCount = ref(0);

// 控制弹窗显示
const showCommentModal = ref(false);

// 评论列表数据
const comments = ref([]);

// 新评论内容
const newComment = ref("");

// 回复相关状态
const replyTo = ref(null); // 被回复的评论
const replyPlaceholder = ref("请输入评论..."); // 输入框提示

// 获取帖子数据
const getPosts = async () => {
  const GET_POSTS_URL = `${API_BASE_URL}/posts/searchByPostId`;
  try {
    const response = await axios.get(GET_POSTS_URL, {
      params: {
        postId: postId,
      },
    });
    if (response.data.code === 200) {
      posts.value = response.data.data;
      // 获取点赞状态和点赞数量
      const likeStatusResponse = await axios.get(`${API_BASE_URL}/like/status/${postId}`, { withCredentials: true });
      if (likeStatusResponse.data.code === 200) {
        isLiked.value = likeStatusResponse.data.isLiked;
      }
      const likeCountResponse = await axios.get(`${API_BASE_URL}/like/count/${postId}`);
      if (likeCountResponse.data.code === 200) {
        likeCount.value = likeCountResponse.data.likeCount;
      }
      // 检查 content 是否是有效的 JSON 字符串
      try {
        posts.value.content = JSON.parse(posts.value.content);
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (error) {
        // 如果不是 JSON 字符串，直接使用原始值
        console.warn("content 不是有效的 JSON 字符串，使用原始值:", posts.value.content);
      }
    }
  } catch (error) {
    ElMessage.error("查询失败" + error.message);
  }
};
// 作者身份状态
const isOwner = ref(false);

// 检查当前用户是否为帖子作者
const checkIsOwner = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/posts/${postId}/isOwner`, { withCredentials: true });
    if (response.data.code === 200) {
      isOwner.value = response.data.isOwner;
    }
  } catch (error) {
    ElMessage.error("判断作者身份失败：" + error.message);
  }
};

// 处理点赞
const handleLike = async () => {
  try {
    if (isLiked.value) {
      const response = await axios.delete(`${API_BASE_URL}/like/${postId}`, { withCredentials: true });
      if (response.data.code === 200) {
        isLiked.value = false;
        likeCount.value = response.data.likeCount;
        ElMessage.success("取消点赞成功");
      }
    } else {
      const response = await axios.post(`${API_BASE_URL}/like/${postId}`, {}, { withCredentials: true });
      if (response.data.code === 200) {
        isLiked.value = true;
        likeCount.value = response.data.likeCount;
        ElMessage.success("点赞成功");
      }
    }
  } catch (error) {
    ElMessage.error("操作失败：" + error.message);
  }
};
//点击用户头像就进入那个用户的主页

// 点击标签搜索
const handleSearchPost = (tag) => {
  const tagName = Array.isArray(tag) ? tag[0] : tag;
  router.push({ name: 'Lates_post', params: { tag_name: tagName } });
};


//查询当前用户信息
const getCurrentUser =async()=>{
  const GET_CURRENT_URL = `${API_BASE_URL}/userInfo`
  const userId = route.params.userId
  try{
    const response = await axios.get(GET_CURRENT_URL,{
      params:{
        userId:userId
      }
    })
    if(response.data.code === 200){
    fans.value = response.data.followerCount;
    followed.value = response.data.followedCount
    }
  }catch (error){
    ElMessage.error("error"+error.message)
  }
}
// 获取评论列表
const getComments = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/comment/${postId}`);
    if (response.data.code === 200) {
      comments.value = response.data.comments.map(comment => ({
        ...comment,
        showReplies: false, // 默认不展开二级评论
        replies: [], // 初始化二级评论为空
      }));
      // 获取二级评论
      await loadReplies();
    }
  } catch (error) {
    ElMessage.error("获取评论失败：" + error.message);
  }
};

// 获取二级评论
const loadReplies = async () => {
  for (const comment of comments.value) {
    try {
      const response = await axios.get(`${API_BASE_URL}/comment/replies/${comment.id}`);
      if (response.data.code === 200) {
        comment.replies = response.data.replies;
      }
    } catch (error) {
      ElMessage.error("获取二级评论失败：" + error.message);
    }
  }
};

// 展开或收起二级评论
const toggleReplies = (comment) => {
  comment.showReplies = !comment.showReplies;
};

// 准备回复
const prepareReply = (comment) => {
  replyTo.value = comment;
  replyPlaceholder.value = `回复 ${comment.username}:`;
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  try {
    const response = await axios.post(`${API_BASE_URL}/comment/saveComment`, null, {
      params:{
        postId: postId,
        parentCommentId: replyTo.value ? replyTo.value.id : null,
        content: newComment.value,
      },
      withCredentials: true });

    if (response.data.code === 200) {
      ElMessage.success("评论成功");
      newComment.value = "";
      replyTo.value = null;
      replyPlaceholder.value = "请输入评论...";
      await getComments(); // 刷新评论列表
      getCurrentUser()
    }
  } catch (error) {
    ElMessage.error("评论失败：" + error.message);
  }
};
// 取消回复
const cancelReply = () => {
  replyTo.value = null;
  replyPlaceholder.value = "请输入评论...";
};
// 关闭弹窗
const handleClose = () => {
  showCommentModal.value = false;
};
// 监听弹窗显示状态
watch(showCommentModal, (newVal) => {
  if (newVal) {
    getComments(); // 打开弹窗时获取评论列表
  }
});
// 关注状态
const isFollowing = ref(false);

// 检查是否已关注
const checkFollowStatus = async () => {
  try {
    const userId = route.params.userId // 被关注用户的 ID
    const response = await axios.get(`${API_BASE_URL}/follow/status/${userId}`, { withCredentials: true });
    if (response.data.code === 200) {
      isFollowing.value = response.data.isFollowing;
    }
  } catch (error) {
    ElMessage.error("获取关注状态失败：" + error.message);
  }
};

// 关注用户
const followUser = async () => {
  try {
    const userId =route.params.userId // 被关注用户的 ID
    const response = await axios.post(`${API_BASE_URL}/follow/${userId}`, {}, { withCredentials: true });
    if (response.data.code === 200) {
      isFollowing.value = true;
      await getCurrentUser()
      ElMessage.success("关注成功");
    }
  } catch (error) {
    ElMessage.error("关注失败：" + error.message);
  }
};

// 取消关注用户
const unfollowUser = async () => {
  try {
    const userId = route.params.userId // 被关注用户的 ID
    const response = await axios.delete(`${API_BASE_URL}/follow/${userId}`, { withCredentials: true });
    if (response.data.code === 200) {
      isFollowing.value = false;
      await getCurrentUser()
      ElMessage.success("取消关注成功");
    }
  } catch (error) {
    ElMessage.error("取消关注失败：" + error.message);
  }
};

// 处理关注按钮点击
const handleFollow = () => {
  if (isFollowing.value) {
    unfollowUser();
  } else {
    followUser();
  }
};
//点击头像进入作者主页
const handleToOther =()=>{
  if(isOwner.value){router.push('/personal_page')}else { const userId = route.params.userId;
    router.push({name:'Other_user',params:{userId:userId}})}

}
// 监听弹窗显示状态
watch(showCommentModal, (newVal) => {
  if (newVal) {
    getComments(); // 打开弹窗时获取评论列表
  }
});
onMounted(() => {
  checkIsOwner();
  getPosts();
  getCurrentUser()
  checkFollowStatus()
});
</script>


<style scoped>
/* 背景组件样式 */
.code-rain-background {
  position: fixed; /* 固定定位 */
  top: 0;
  left: 0;
  width: 100%; /* 覆盖整个页面宽度 */
  height: 100%; /* 覆盖整个页面高度 */
  z-index: -1; /* 确保在其他内容下方 */
}
.personal_card {
  display: flex;
  position: absolute;
  left: 15%;
  top: 10%;
  width: 80vw;
  height: 150px;
  background-color: #007bff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影 */
  border-radius: 10px; /* 添加圆角 */
}

.card_left {
  display: flex;
}

/* 图片容器样式 */
.img {
  width: 90px;
  height: 90px;
  overflow: hidden;
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  left: 5px;
  top: -10px;
  justify-content: center;
  align-items: center;
  margin: 3px;
  background-color: #dddddd;
}

/* 图片样式 */
.img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.name {
  display: flex;
  margin: 20px 0 0 20px;
  font-weight: bolder;
  font-size: 30px;
}

.follow {
  position: absolute;
  right: 20px;
  top: 20px;
}

.card_middle {
  display: flex;
  flex: 1;
}

.fans {
  display: flex;
  flex-direction: column;
  position: absolute;
  left: 7%;
  top: 50%;
}

.post_content {
  overflow: auto;
  display: flex;
  position: absolute;
  flex-direction: column;
  left: 15%;
  top: 30%;
  width: 80vw;
  height: 60vh;
  background-color: wheat;
  border: 1px solid black;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影 */
  border-radius: 10px; /* 添加圆角 */
}

.like {
  position: fixed;
  justify-content: flex-end;
  background-color: white;
  padding-right: 20px;
  right: 7%;
  top: 85%;
}

.like_comment {
  position: absolute;
  right: 0;
  display: flex;
  gap: 20px;
}

.like_button,
.comment_button {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 5px; /* 图标、文本和数量之间的间距 */
  cursor: pointer;
  font-size: 16px;
}

.like_button .count,
.comment_button .count {
  font-size: 14px; /* 数量字体大小 */
  font-weight: bold; /* 加粗 */
  margin-left: 3px; /* 数量与文本之间的间距 */
}

.like_button i,
.comment_button i {
  font-size: 18px; /* 图标大小 */
}

.like_button .fa-heart {
  color: #ccc;
}

.like_button .fa-heart.liked {
  color: red;
}

.comment_button .fa-comment {
  color: #007bff;
}
.title {
  display: flex;
  font-size: 50px;
  font-weight: bold;
  margin: 10px 0 0 20px;
}

.detail_content {
  margin: 20px;
}

.tag {
  cursor: pointer;
}

.tag:hover {
  color: hotpink;
}
.main-comment {
  cursor: pointer; /* 点击主评论时展开或收起二级评论 */
}
.like_comment span {
  height: 50px;
  width: 50px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.like_comment .fa-heart {
  color: #ccc;
}

.like_comment .fa-heart.liked {
  color: red;
}

.like_comment .fa-comment,
.like_comment .fa-comments {
  color: #007bff;
}/* 背景组件样式 */
.code-rain-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; /* 确保在其他内容下方 */
}

/* 评论容器样式 */
.comment-container {
  display: flex;
  flex-direction: column;
  height: 400px; /* 设置弹窗内容区域的高度 */
}

/* 评论列表样式 */
.comment-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

/* 评论项样式（主评论和二级评论共用基础样式） */
.comment-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

/* 主评论样式 */
.main-comment {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 10px;
  cursor: pointer; /* 鼠标悬停可点击 */
  background-color: #fff;
}

.comment-header {
  font-weight: bold;
  margin-bottom: 5px;
}

.floor-number {
  color: #666;
  margin-right: 10px; /* 楼层编号与用户名的间距 */
}

.comment-user {
  font-weight: bold;
  color: #007bff; /* 用户名使用蓝色 */
}

.comment-content {
  margin-top: 5px;
  color: #333; /* 评论内容颜色 */
  cursor: pointer; /* 鼠标悬浮显示为可点击 */
}

.comment-content:hover {
  background: #f5f5f5; /* 鼠标悬浮高亮 */
}

/* 评论操作按钮 */
.comment-actions {
  text-align: right;
  margin-top: 5px;
}

/* 二级评论样式 */
.replies {
  margin-left: 20px; /* 二级评论缩进 */
  border-left: 2px solid #eee; /* 左侧边框以区分层级 */
  padding-left: 10px; /* 评论内容与边框间距 */
}

.reply-item {
  margin-top: 10px;
  padding: 5px;
  border-bottom: 1px solid #eee;
  background-color: #fafafa; /* 二级评论背景色稍浅，便于区分 */
}

.reply-item .comment-header {
  font-weight: bold;
  margin-bottom: 5px;
}

.reply-item .floor-number {
  color: #666; /* 二级评论楼层编号颜色 */
  margin-right: 10px;
}

.reply-item .comment-user {
  font-weight: bold;
  color: #007bff; /* 二级评论用户名颜色 */
}

.reply-item .comment-content {
  color: #333;
  cursor: pointer;
}

.reply-item .comment-content:hover {
  background: #f5f5f5; /* 鼠标悬浮高亮 */
}

/* 回复输入框样式 */
.comment-input {
  position: sticky; /* 固定在底部 */
  bottom: 0;
  background-color: #fff;
  padding: 10px;
  border-top: 1px solid #eee;
}

/* 输入框样式 */
.comment-input el-input {
  width: 100%;
  font-size: 14px;
}

.comment-input el-button {
  margin-left: 10px;
  white-space: nowrap;
}

</style>
